package com.book.service.impl;

import com.book.entity.Account;
import com.book.mapper.AccountMapper;
import com.book.service.AccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author SuperYu  2024/7/30
 */
@Service
public class AccountServiceImpl implements AccountService {

    AccountMapper accountMapper;

    @Autowired
    public void setAccountMapper(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    @Override
    public Account findAccountByLogin(String name) {
        Example example = new Example(Account.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("userName",name);
        return accountMapper.selectOneByExample(example);

    }

    @Override
    public int addAccount(Account account) {
        return accountMapper.insertSelective(account);
    }

    @Override
    @Cacheable(value="account", key="#root.methodName+#root.args[0]+#root.args[1]")
    public PageInfo<Account> findAccountByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Account> list = accountMapper.selectAll();
        return new PageInfo<>(list);
    }

    @Override
    @CacheEvict(value="account", allEntries = true)
    public int deleteAccountById(int id) {
        return accountMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Account> findAllAccount() {
        return accountMapper.selectAll();
    }

    @Override
    public Account findAccountByEdit(int id, String username) {

        Example example = new Example(Account.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("userName",username);
        c.andNotEqualTo("id", id);

        return accountMapper.selectOneByExample(example);
    }
}
